const crypto = require('crypto');

/**
 * key && iv
 */
const defaultKey = '1234567887654321';
const defaultIv = '8765432112345678';

/**
 * 加密
 */
const encrypt = (originalContent, key = defaultKey, iv = defaultIv) => {
  const strContent = JSON.stringify(originalContent);
  const cipheriv = crypto.createCipheriv('aes128', key, iv);
  const code = cipheriv.update(strContent, 'utf-8', 'hex');
  const encryptContent = code + cipheriv.final('hex');
  return encryptContent;
};

/**
 * 解密
 */
const decrypt = (encryptContent, key = defaultKey, iv = defaultIv) => {
  const decipheriv = crypto.createDecipheriv('aes128', key, iv);
  const code = decipheriv.update(encryptContent, 'hex', 'utf-8');
  const originalContent = JSON.parse(code + decipheriv.final('utf-8'));
  return originalContent;
};

export { encrypt, decrypt };
